// borrow.js
// pages/apply/apply.js
// pages/apply/apply.js
Page({
    data: {
      currentUser: {},
      items: [],
      quantities: [], // 用户输入的领用数量
      filteredItems: [] // 库存大于0的物品列表
    },
  
    onLoad: function () {
      const currentUser = wx.getStorageSync('currentUser');
      this.setData({ currentUser });
  
      // 获取可领用的物品列表（假设从云数据库中获取）
      this.getItems();
    },
  
    getItems: function () {
      const db = wx.cloud.database();
      db.collection('items').get().then(res => {
        const items = res.data.map(item => ({
          materialName: item.materialName,
          materialNumber: item.materialNumber,
          quantity: item.quantity || 0, // 使用quantity字段表示库存，如果没有库存，默认为0
        }));
        
        // 过滤掉没有库存的物品
        const filteredItems = items.filter(item => item.quantity > 0);
  
        // 初始化 quantities 数组
        const quantities = new Array(filteredItems.length).fill(0);
  
        this.setData({ items, filteredItems, quantities });
      }).catch(err => {
        console.error('获取物品列表失败', err);
      });
    },
  
    onQuantityChange: function (e) {
      const index = e.currentTarget.dataset.index;
      const value = e.detail.value;
      const quantities = this.data.quantities.slice();
      quantities[index] = value;
      this.setData({ quantities });
    },
  
    submitApplication: function () {
      const { currentUser, filteredItems, quantities } = this.data;
  
      if (!currentUser.username) {
        wx.showToast({ title: '请先登录', icon: 'none' });
        return;
      }
  
      const applicationDate = new Date();
      const recordsData = {
        applicant: currentUser.username,
        applicationDate: applicationDate,
        items: filteredItems.map((item, index) => ({
          materialName: item.materialName,
          materialNumber: item.materialNumber,
          quantity: item.quantity, // 当前库存量
          requestedQuantity: quantities[index] // 用户请求的数量
        }))
      };
  
      const db = wx.cloud.database();
      db.collection('records').add({
        data: recordsData
      }).then(res => {
        wx.showToast({ title: '申请成功', icon: 'success' });
        this.setData({ quantities: new Array(this.data.filteredItems.length).fill(0) });
      }).catch(err => {
        console.error('提交申请失败', err);
        wx.showToast({ title: '申请失败，请稍后重试', icon: 'none' });
      });
    }
  });